package com.sbj.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import cn.zhxu.bs.BeanSearcher;
import cn.zhxu.bs.SearchResult;
import cn.zhxu.bs.util.MapUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sbj.dto.req.AddressReq;
import com.sbj.dto.res.AddressRes;
import com.sbj.entity.Address;
import com.sbj.mapper.AddressMapper;
import com.sbj.service.IAddressService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmh.framework.constants.Constants;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author summer
 * @since 2024/08/10 10:02:39
 */
@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements IAddressService {

    @Override
    public void addAddress(AddressReq addressReq) {
        Integer memberId= Convert.convert(Integer.class, StpUtil.getLoginId());
        if(addressReq.getIsDefault()){
            LambdaQueryWrapper<Address> eq = Wrappers.lambdaQuery(Address.class).eq(Address::getMemberId, memberId).eq(Address::getIsGive, Constants.ONE);
            Address address = new Address();
            address.setIsDefault(true);
            this.update(address, eq);
        }
        Address convert = Convert.convert(Address.class, addressReq);
        convert.setMemberId(memberId);
        this.saveOrUpdate(convert);
    }

    private final BeanSearcher beanSearcher;

    @Override
    public List<AddressRes> lists() {
        Map<String, Object> build = MapUtils.builder().field(AddressRes::getMemberId, StpUtil.getLoginId())
                .field(AddressRes::getDeleted, Constants.ZERO).build();
        SearchResult<AddressRes> search = beanSearcher.search(AddressRes.class, build);
        return search.getDataList();
    }

    @Override
    public AddressRes memberAddress(Integer id) {
        Map<String, Object> build = MapUtils.builder().field(AddressRes::getMemberId,id)
                .field(AddressRes::getDeleted, Constants.ZERO).field(AddressRes::getIsDefault,1).build();
        return beanSearcher.searchFirst(AddressRes.class,build);
    }
}
